import { useEffect, useState } from "react"
import { reqAddComment, reqGetCBIID } from "../../api/comment"
import style from "./index.module.css"
import { CommentItem } from "../CommentItem"
import { Button } from "antd"
import { UserOutlined } from "@ant-design/icons"
import "@wangeditor/editor/dist/css/style.css" // 引入 css
import { Editor, Toolbar } from "@wangeditor/editor-for-react"
import { IDomEditor, IEditorConfig, IToolbarConfig } from "@wangeditor/editor"
import { useSelector } from "react-redux"
import { ROOT_STATE } from "../../store"
import { CommentItem as Comment } from "../../Types/Api/comment"
type Props = {
  issueId: string
  typeId: string
}
export const Discuss = ({ issueId, typeId }: Props) => {
  // 用户信息，
  const { userInfo: user, isLogin } = useSelector(
    (state: ROOT_STATE) => state.userReducer
  )
  // const user = null
  // 富文本相关变量
  const [editor, setEditor] = useState<IDomEditor | null>(null)
  const [html, setHtml] = useState("")
  const toolbarConfig: Partial<IToolbarConfig> = {}
  const editorConfig: Partial<IEditorConfig> = {
    placeholder: "请输入内容...",
  }
  useEffect(() => {
    return () => {
      if (editor == null) return
      editor.destroy()
      setEditor(null)
    }
  }, [editor])
  //   issueId => coments
  const [pageInfo, setPageInfo] = useState({
    current: 1,
    pageSize: 5,
    total: 1,
  })
  const [commentList, setCommentList] = useState<JSX.Element[]>([])

  const getIssueComments = async () => {
    const { data: res } = await reqGetCBIID(issueId, {
      current: pageInfo.current,
      pageSize: pageInfo.pageSize,
    })
    setPageInfo({
      ...pageInfo,
      total: res.count,
    })
    // res.data 进行页面渲染
    const arr = res.data.map((item) => (
      <CommentItem key={item._id} info={item}></CommentItem>
    ))
    setCommentList(arr)
  }

  // 添加评论
  const addComment = async () => {
    // console.log("tianjia ")
    const obj: Comment = {
      userId: user._id,
      issueId,
      typeId,
      commentType: 1,
      commentContent: html,
    }
    if (html === "<p><br></p>") {
      console.log("请输入内容")
      return
    }
    console.log(html)
    await reqAddComment(obj)
    getIssueComments()
    setHtml("")
  }
  useEffect(() => {
    if (issueId) {
      getIssueComments()
    }
  }, [])
  return (
    <div className={style.wrapper}>
      {/* 发表评论 */}
      <div className={style.editWrapper}>
        {/* 头像 */}
        {isLogin ? (
          <img
            className={style.user}
            src={import.meta.env.VITE_APP_BASE_SERVICE + user.avatar}
          />
        ) : (
          <UserOutlined className={style.user} />
        )}
        {/* 富文本 */}
        <div style={{ border: "1px solid #ccc", zIndex: 10, width: "70%" }}>
          <Toolbar
            editor={editor}
            defaultConfig={toolbarConfig}
            mode="default"
            style={{ borderBottom: "1px solid #ccc" }}
          />
          <Editor
            defaultConfig={editorConfig}
            value={html}
            onCreated={setEditor}
            onChange={(editor) => setHtml(editor.getHtml())}
            mode="default"
            style={{ height: "200px", overflowY: "hidden" }}
          />
        </div>
      </div>
      {/* 发送评论按钮 */}
      <Button
        onClick={addComment}
        disabled={!isLogin}
        className={style.sendComment}
      >
        添加评论
      </Button>
      {/* 展示评论 */}
      <div className={style.commentsWrapper}>
        <h3>当前评论</h3>
        {/* 评论列表 */}
        {/* 评论组件的集合 */}
        {commentList}
        {/* 评论翻页 */}
      </div>
    </div>
  )
}
